package server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import users.Doctor;
import users.Nurse;
import users.Patient;
import users.User;

public class Journal {
	private Doctor doc;
	private Nurse nurse;
	private Patient patient;
	private int journalNumber;
	private String division;
	private String data;
	
	public Journal(String file) {
		String[] split = file.split("/");
		
		this.patient = new Patient(split[0]);
		this.journalNumber = Integer.parseInt(split[1]);
		
		try {
			BufferedReader br = new BufferedReader(new FileReader("journals/" + patient.getName() + "/" + journalNumber));
			
			division = br.readLine();
			doc = new Doctor(br.readLine(), division);
			nurse = new Nurse(br.readLine(), division);
			
			data = division + "\n" + doc.getName() + "\n" + nurse.getName() + "\n";
			String line = null;
			while ((line = br.readLine()) != null) {
				data += line + "\n";
			}
			
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Journal(Patient patient, User doc, Nurse nurse) {
		this.patient = patient;
		this.division = doc.getDivision();
		this.doc = (Doctor) doc;
		this.nurse = nurse;
		
		File dir = new File("journals/" + patient.getName());
		
		dir.mkdir();
		
		journalNumber = new File("journals/" + patient.getName()).list().length;
		
		data = division + "\n" + doc.getName() + "\n" + nurse.getName() + "\n-----------------------\n";
		
		writeData(data);
	}

	public boolean canRead(User user) {
		int userType = user.getType();
		
		switch (userType) {
		case User.GOVERNMENT:
			return true;
		case User.DOCTOR:
			return user.equals(doc) || user.getDivision().equals(division);
		case User.NURSE:
			return user.equals(nurse) || user.getDivision().equals(division);
		case User.PATIENT:
			return user.equals(patient);
		default:
			return false;
		}
	}
	
	public boolean canWrite(User user) {
		int userType = user.getType();
		
		switch (userType) {
		case User.DOCTOR:
			return user.equals(doc);
		case User.NURSE:
			return user.equals(nurse);
		default:
			return false;
		}
	}
	
	public boolean canDelete(User user) {
		return user.getType() == User.GOVERNMENT;
	}
	
	public String getData() {
		return data;
	}

	public void writeData(String journalContents) {
		data = journalContents;
		try {
			PrintWriter pw = new PrintWriter("journals/" + patient.getName() + "/" + journalNumber);
			pw.write(journalContents);
			pw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public String getFilename() {
		return patient.getName() + "/" + journalNumber;
	}
}
